#include "iniconfigfile.h"

namespace tool {

INIConfigFile::INIConfigFile() {
	is_open = false;
}

INIConfigFile::~INIConfigFile() {
	if(is_open) {
		in.close();
	}
}

bool INIConfigFile::IsLoad() {
	return is_open;
}

uint32_t INIConfigFile::Load(std::string filename) {
	char line[512];
	bool is_get = false;
	std::string key;
	VALUE_LIST value_list;

	if(is_open) {
		in.close();
	}

	is_open = true;
	in.open(filename.c_str(), std::ios::in);
	if(in.is_open() == false) {
		return false;
	}

	while(!in.eof()) {
		in.getline(line, 512);
		is_get = GetKeyValue(line, key, value_list);
		if(!is_get || key.size() == 0 || value_list.size() == 0) {
			continue;
		}
		value_map.insert(std::make_pair(key, value_list));
	}
	return is_open;
}

uint32_t INIConfigFile::GetValue(std::string key, uint32_t& v) {
	uint32_t value = 0;

	return GetValue(key, v, 0);
}

uint32_t INIConfigFile::GetValue(std::string key, uint32_t& v, int index) {
	VALUE_LIST::iterator value_it;
	VALUE_MAP::iterator it = value_map.find(key);

	if(it == value_map.end() || it->second.size() <= 0 ||		
				index >= it->second.size()) {
		v = 0;
		return false;
	}

	value_it = it->second.begin();
	advance(value_it, index);
	v = atoi(value_it->c_str());
	return true;
}

uint32_t INIConfigFile::GetValue(std::string key, std::string& v) {
	VALUE_MAP::iterator it = value_map.find(key);

	if(it == value_map.end() || it->second.size() <= 0) {
		v = "";
		return false;
	}
	v = it->second.begin()->c_str();
	return true;
}

uint32_t INIConfigFile::GetValue(std::string key, 
			std::map<uint32_t, uint32_t>& v) {

}

uint32_t INIConfigFile::GetValue(std::string key, std::list<uint32_t>& v) {
	uint32_t value = 0;

	for(int i = 0; GetValue(key, value, i); i++) {
		v.push_back(value);
	}
	return true;
}

uint32_t INIConfigFile::GetValue(std::string key, std::list<std::string>& v) {

}

uint32_t INIConfigFile::GetValue(std::string key, std::map<uint32_t, std::string>& v) {

}

bool INIConfigFile::GetKeyValue(char* line, std::string& key, VALUE_LIST& value_list) {
	int is_find = false;
	int len = strlen(line);
	std::string value;

	key = "";
	value = "";
	value_list.clear();
	for(int i = 0; i < len; i++) {
		if(line[i] == '#') {
			break;
		}

		if(line[i] == '=') {
			is_find = true;
		}
		else {
			if(is_find == false) {
				if(line[i] == ' ') { //对于Key，不能存在[空格]
					continue;
				}
				key += line[i];
			}
			else {
				if(line[i] == ' ' && value.size() == 0) {
					continue;
				}

				if(line[i] == ',') {
					if(value.size() > 0) {
						value_list.push_back(value);
						value = "";
					}
				}
				else {
					value += line[i];
				}
			}
		}
	}

	if(value.size() > 0) {
		value_list.push_back(value);
	}
	return is_find;
}

}
